import sys
import os
import re
from pathlib import Path
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLineEdit, QCheckBox,
                             QLabel, QMessageBox, QComboBox, QFileDialog,
                             QTextEdit, QMainWindow, QSizePolicy)
from PyQt5.QtCore import QThread, pyqtSignal, QSettings
from PyQt5.QtGui import QIcon
import subprocess
from urllib.parse import urlparse


class DownloadThread(QThread):
    finished_signal = pyqtSignal()
    info_signal = pyqtSignal(str)
    file_name_signal = pyqtSignal(str)  # 新增：发送文件路径

    def __init__(self, cmd):
        super().__init__()
        self.cmd = cmd
        self.file_name = None  # 存储下载文件的路径
        self.found_title = False  # 标志是否已经找到文件名
        self.found_container = False  # 标志是否已经找到文件名
        self.title = None  # 存储提取到的标题
        self.container = None  # 默认容器格式
        self.stop_flag = False  # 停止标志

    def run(self):
        try:
            if sys.platform == 'win32':
                # 对于 Python 3.7 及以上版本
                creation_flags = subprocess.CREATE_NO_WINDOW
            else:
                creation_flags = 0
            # 尝试使用 utf-8 编码
            process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                       universal_newlines=True, encoding='utf-8', creationflags=creation_flags)
            for line in process.stdout:
                if self.stop_flag:  # 检查停止标志
                    process.terminate()  # 终止子进程
                    break
                self.info_signal.emit(line.strip())
                # 提取文件名
                if not self.found_title and "title:" in line:
                    # 提取标题
                    match = re.search(r'title:\s*(.+)', line)
                    if match:
                        self.title = match.group(1).strip()  # 去除可能的多余空格
                        self.title += "[00]"
                        self.found_title = True  # 设置标志为已找到

                if not self.found_container and "container: " in line:
                    # 提取标题
                    match = re.search(r'container:\s*(.+)', line)
                    if match:
                        self.container = match.group(1).strip()  # 去除可能的多余空格
                        self.found_container = True  # 设置标志为已找到

            process.wait()
            if process.returncode == 0:
                self.finished_signal.emit()
                if self.title and self.container:
                    # 组合成文件路径
                    self.file_name = f"{self.title}.{self.container}"
                    self.file_name_signal.emit(self.file_name)
            else:
                self.info_signal.emit(f"下载失败，错误码：{process.returncode}")
        except Exception as e:
            output = f"Error: {e}"
            self.info_signal.emit(output)

    def stop(self):
        self.stop_flag = True

    # def merge_audio_video(self):
    #     if self.title:
    #         video_file = os.path.join(self.output_dir, f"{self.title}.mp4")
    #         audio_file = os.path.join(self.output_dir, f"{self.title}.m4a")
    #         merged_file = os.path.join(self.output_dir, f"{self.title}_merged.mp4")
    #
    #         if os.path.exists(video_file) and os.path.exists(audio_file):
    #             self.info_signal.emit("开始合并音视频...")
    #             ffmpeg_cmd = [
    #                 "ffmpeg",
    #                 "-i", video_file,
    #                 "-i", audio_file,
    #                 "-c:v", "copy",
    #                 "-c:a", "aac",
    #                 "-strict", "experimental",
    #                 merged_file
    #             ]
    #             try:
    #                 process = subprocess.run(ffmpeg_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
    #                                          text=True, cwd=self.output_dir)
    #                 self.info_signal.emit("音视频合并完成！")
    #                 self.file_path = merged_file
    #                 self.file_path_signal.emit(merged_file)
    #             except subprocess.CalledProcessError as e:
    #                 self.info_signal.emit(f"音视频合并失败：{e.output}")
    #             finally:
    #                 # 删除原始的音视频文件
    #                 if os.path.exists(video_file):
    #                     os.remove(video_file)
    #                 if os.path.exists(audio_file):
    #                     os.remove(audio_file)


class InfoThread(QThread):
    info_signal = pyqtSignal(str)
    finished_signal = pyqtSignal()

    def __init__(self, cmd):
        super().__init__()
        self.cmd = cmd
        self.stop_flag = False
        self.process = None

    def run(self):
        try:
            if sys.platform == 'win32':
                # 对于 Python 3.7 及以上版本
                creation_flags = subprocess.CREATE_NO_WINDOW
            else:
                creation_flags = 0
            self.info_signal.emit("正在查询...")
            # 尝试使用 utf-8 编码
            self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                       universal_newlines=True, encoding='utf-8', creationflags=creation_flags)

            output, _ = self.process.communicate()
            self.info_signal.emit(output)
            self.process.wait()
            if self.process.returncode == 0:
                self.finished_signal.emit()
            else:
                self.info_signal.emit(f"查询失败，错误码：{self.process.returncode}")
        except Exception as e:
            # 如果仍然失败，捕获所有其他异常
            output = f"Error: {e}"
            self.info_signal.emit(output)

    def stop(self):
        self.stop_flag = True
        self.process.terminate()


class PlayerThread(QThread):
    def __init__(self, cmd):
        super().__init__()
        self.cmd = cmd

    def run(self):
        try:
            # 尝试使用 utf-8 编码
            process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                            universal_newlines=True, encoding='utf-8')

            process.wait()
            if process.returncode != 0:
                QMessageBox.warning(self, "播放失败", f"播放失败，错误码：{self.process.returncode}")
        except Exception as e:
            # 如果仍然失败，捕获所有其他异常
            QMessageBox.warning(self, "播放失败", f"播放失败，Error: {e}")


class DownloadWindow(QMainWindow):
    def __init__(self, title, cmd, settings):
        super().__init__()
        self.setStyleSheet("""
                    QWidget {
                        background-color: #2a2a2a;
                        color: #ffffff;
                    }
                    QMainWindow {
                        background-color: #2a2a2a;
                        color: #ffffff;
                    }
                    QLabel {
                        color: #ffffff;
                    }
                    QTextEdit {
                        background-color: #3a3a3a;
                        color: #ffffff;
                        padding: 10px;
                        border: 1px solid #5a5a5a;
                        border-radius: 5px;
                    }
                    QPushButton {
                        background-color: #3a3a3a;
                        color: #ffffff;
                        padding: 10px;
                        border: none;
                        border-radius: 5px;
                    }
                    QPushButton:hover {
                        background-color: #5a5a5a;
                    }
                """)
        self.setWindowTitle(title)
        self.setGeometry(680, 450, 1200, 800)
        self.setWindowIcon(QIcon(os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "logo.png")))

        self.output_dir = settings.value("output_dir_input", "")
        self.pre_fix = settings.value("prefix_input", "")
        self.pre_fix_checkbox = settings.value("prefix_checkbox", False, type=bool)
        self.output_name = settings.value("output_filename_input", "")
        self.output_name_checkbox = settings.value("output_filename_checkbox", False, type=bool)
        self.file_path = None  # 初始化文件路径

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout(self.central_widget)

        # 设置 command_label 为多行显示
        self.command_label = QLabel("下载命令: " + ' '.join(cmd))
        self.command_label.setWordWrap(True)  # 允许文本自动换行
        self.command_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        # self.command_label.setStyleSheet("""color: #ffffff;""")
        self.layout.addWidget(self.command_label)

        self.info_text = QTextEdit(self)
        self.info_text.setReadOnly(True)
        self.info_text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 允许文本区域自动扩展
        self.layout.addWidget(self.info_text)

        self.open_layout = QHBoxLayout(self.central_widget)
        self.open_file_button = QPushButton("打开文件", self)
        self.open_file_button.clicked.connect(self.open_file)
        self.open_file_button.setEnabled(False)  # 初始禁用
        self.open_layout.addWidget(self.open_file_button)

        self.open_folder_button = QPushButton("打开文件夹", self)
        self.open_folder_button.clicked.connect(lambda: self.open_folder(self.output_dir))
        self.open_layout.addWidget(self.open_folder_button)

        self.layout.addLayout(self.open_layout)

        try:
                self.thread = DownloadThread(cmd)
                self.thread.info_signal.connect(self.update_info)
                self.thread.finished_signal.connect(self.finish_download)
                self.thread.file_name_signal.connect(self.set_file_path)  # 连接文件路径信号
                self.thread.start()
        except Exception as e:
            self.info_text.append(f"下载失败，错误码：{e}")
            import traceback
            traceback.print_exc()

    def update_info(self, info):
        self.info_text.append(info)

    def finish_download(self):
        self.info_text.append("下载完成！")
        self.open_file_button.setEnabled(True)  # 下载完成后启用“打开文件”按钮
        QMessageBox.warning(self, "提示", "下载完成！！")

    def set_file_path(self, file_name):
        # 这里需要根据文件的前缀后缀或自定义 自定义文件名来修改最终的文件名
        basename, extension = os.path.splitext(file_name)
        if self.output_name_checkbox and self.output_name:
            file_name = self.output_name
        else:
            if self.pre_fix_checkbox and self.pre_fix:
                file_name = f"[{self.pre_fix}]{basename}{extension}"

        self.file_path = os.path.join(self.output_dir, file_name)
        self.info_text.append(f"文件已保存到: {self.file_path}")

    def open_file(self):
        # 打开下载的文件
        if self.file_path and os.path.exists(self.file_path):
            os.startfile(self.file_path)
        else:
            QMessageBox.warning(self, "警告", "文件不存在！")

    def open_folder(self, folder_path):
        if os.path.exists(folder_path):
            os.startfile(folder_path)
        else:
            QMessageBox.warning(self, "警告", "文件夹不存在！")

    def closeEvent(self, event):
        # 在关闭窗口时停止下载线程
        if self.thread.isRunning():
            self.thread.stop()
            #self.thread.wait()  # 等待线程完全停止
        event.accept()


class InfoWindow(QMainWindow):
    def __init__(self, title, cmd):
        super().__init__()
        self.setStyleSheet("""
                    QWidget {
                        background-color: #2a2a2a;
                        color: #ffffff;
                    }
                    QMainWindow {
                        background-color: #2a2a2a;
                        color: #ffffff;
                    }
                    QLabel {
                        color: #ffffff;
                    }
                    QTextEdit {
                        background-color: #3a3a3a;
                        color: #ffffff;
                        padding: 10px;
                        border: 1px solid #5a5a5a;
                        border-radius: 5px;
                    }
                    QPushButton {
                        background-color: #3a3a3a;
                        color: #ffffff;
                        padding: 10px;
                        border: none;
                        border-radius: 5px;
                    }
                    QPushButton:hover {
                        background-color: #5a5a5a;
                    }
                    """)
        self.setWindowTitle(title)
        self.setGeometry(680, 450, 1200, 800)
        self.setWindowIcon(QIcon(os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "logo.png")))

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.layout = QVBoxLayout(self.central_widget)

        # 设置 command_label 为多行显示
        self.command_label = QLabel("查看命令: " + ' '.join(cmd))
        self.command_label.setWordWrap(True)  # 允许文本自动换行
        self.command_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        # self.command_label.setStyleSheet("""color: #ffffff;""")
        self.layout.addWidget(self.command_label)

        self.info_text = QTextEdit(self)
        self.info_text.setReadOnly(True)
        self.info_text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 允许文本区域自动扩展
        self.layout.addWidget(self.info_text)

        self.open_folder_button = QPushButton("关闭", self)
        self.open_folder_button.clicked.connect(lambda: self.close)
        self.layout.addWidget(self.open_folder_button)

        try:
            self.thread = InfoThread(cmd)
            self.thread.info_signal.connect(self.update_info)
            self.thread.finished_signal.connect(self.finish_query)
            self.thread.start()
        except Exception as e:
            self.info_text.append(f"查看失败，错误码：{e}")
            import traceback
            traceback.print_exc()

    def update_info(self, info):
        self.info_text.append(info)

    def finish_query(self):
        self.info_text.append("查询完成！")
        QMessageBox.warning(self, "提示", "查询完成！！")

    def closeEvent(self, event):
        # 在关闭窗口时停止下载线程
        if self.thread.isRunning():
            self.thread.stop()
            # self.thread.wait()  # 等待线程完全停止
        event.accept()


class DownloaderApp(QWidget):
    def __init__(self):
        super().__init__()
        self.settings = QSettings("YourCompany", "DownloaderApp")
        self.initUI()
        self.load_settings()

    def initUI(self):
        self.setStyleSheet("""
            QWidget {
                background-color: #2a2a2a;
                color: #ffffff;
            }
            QLineEdit {
                background-color: #3a3a3a;
                color: #ffffff;
                padding: 10px;
                border: 1px solid #5a5a5a;
                border-radius: 5px;
            }
            QPushButton {
                background-color: #5a5a5a;
                color: #ffffff;
                padding: 10px;
                border: none;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #6a6a6a;
            }
            QCheckBox {
                color: #ffffff;
            }
            QListWidget {
                background-color: #3a3a3a;
                color: #ffffff;
                padding: 5px;
                border: 1px solid #5a5a5a;
                border-radius: 5px;
            }
            QProgressBar {
                border: 1px solid #5a5a5a;
                background-color: #4a4a4a;
            }
            QProgressBar::chunk {
                background-color: #5cb85c; /* 设置进度条的颜色 */
            }
        """)

        main_layout = QVBoxLayout()

        # URL 输入框
        url_layout = QHBoxLayout()
        self.url_input = QLineEdit(self)
        self.url_input.setPlaceholderText("输入下载地址")
        self.url_input.setMinimumHeight(40)  # 调整输入框高度
        url_layout.addWidget(self.url_input)
        main_layout.addLayout(url_layout)

        # 按钮布局
        button_layout = QHBoxLayout()
        self.info_type_combo = QComboBox(self)
        self.info_type_combo.addItems(["Info", "Info with url", "JSON Format"])
        self.info_type_combo.setMaximumSize(150, 40)
        self.info_type_combo.currentTextChanged.connect(
            lambda: self.settings.setValue("info_type_combo", self.info_type_combo.currentText()))
        button_layout.addWidget(self.info_type_combo)

        # 查看信息按钮
        self.info_btn = QPushButton('查看信息', self)
        self.info_btn.setMinimumHeight(40)
        self.info_btn.clicked.connect(self.show_info)
        button_layout.addWidget(self.info_btn)

        self.download_btn = QPushButton('开始下载', self)
        self.download_btn.setMinimumHeight(40)  # 调整按钮高度
        self.download_btn.clicked.connect(self.start_download)
        button_layout.addWidget(self.download_btn)

        # 播放按钮
        # self.player_input = QLineEdit(self)
        # self.player_input.setPlaceholderText("输入播放器命令（如: vlc, mpv）")
        # self.player_input.textChanged.connect(
        #     lambda: self.settings.setValue("player_input", self.player_input.text()))
        # self.player_input.setMaximumSize(300, 40)
        # self.play_btn = QPushButton('播放视频', self)
        # self.play_btn.setMinimumHeight(40)
        # self.play_btn.clicked.connect(self.play_video)
        # button_layout.addWidget(self.player_input)
        # button_layout.addWidget(self.play_btn)

        main_layout.addLayout(button_layout)

        # 下载选项
        self.options_layout = QVBoxLayout()

        # 不合并
        self.no_merge_checkbox = QCheckBox("不合并视频部分 (-n)")
        self.no_merge_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.no_merge_checkbox))
        self.no_merge_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("no_merge_checkbox", self.no_merge_checkbox.isChecked())
        )
        self.options_layout.addWidget(self.no_merge_checkbox)

        # 不下载字幕
        self.no_caption_checkbox = QCheckBox("不下载字幕(字幕、歌词、舞蹈等) (--no-caption)")
        self.no_caption_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.no_caption_checkbox))
        self.no_caption_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("no_caption_checkbox", self.no_caption_checkbox.isChecked()))
        self.options_layout.addWidget(self.no_caption_checkbox)

        # 后缀选项
        self.postfix_checkbox = QCheckBox("后缀选项 (--post)")
        self.postfix_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.postfix_checkbox))
        self.postfix_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("postfix_checkbox", self.postfix_checkbox.isChecked()))
        self.options_layout.addWidget(self.postfix_checkbox)

        # 前缀选项
        self.prefix_checkbox = QCheckBox("前缀选项 (--pre):")
        self.prefix_input = QLineEdit(self)
        self.prefix_input.setEnabled(False)
        self.prefix_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.prefix_checkbox, self.prefix_input))
        self.prefix_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("prefix_checkbox", self.prefix_checkbox.isChecked()))
        self.prefix_input.textChanged.connect(
            lambda: self.settings.setValue("prefix_input", self.prefix_input.text()))
        self.options_layout.addWidget(self.prefix_checkbox)
        self.options_layout.addWidget(self.prefix_input)

        # 新增的参数
        self.force_checkbox = QCheckBox("强制覆盖文件 (-f)")
        self.force_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.force_checkbox))
        self.force_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("force_checkbox", self.force_checkbox.isChecked()))
        self.options_layout.addWidget(self.force_checkbox)

        self.skip_checkbox = QCheckBox("跳过已有文件大小检查 (--skip-existing-file-size-check)")
        self.skip_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.skip_checkbox))
        self.skip_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("skip_checkbox", self.skip_checkbox.isChecked())
        )
        self.options_layout.addWidget(self.skip_checkbox)

        # 视频格式
        self.format_checkbox = QCheckBox("视频格式 (-F):")
        self.format_input = QLineEdit(self)
        self.format_input.setEnabled(False)
        self.format_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.format_checkbox, self.format_input))
        self.format_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("format_checkbox", self.format_checkbox.isChecked()))
        self.format_input.textChanged.connect(
            lambda: self.settings.setValue("format_input", self.format_input.text()))

        self.options_layout.addWidget(self.format_checkbox)
        self.options_layout.addWidget(self.format_input)

        # 输出文件名
        self.output_filename_checkbox = QCheckBox("输出文件名 (-O):")
        self.output_filename_input = QLineEdit(self)
        self.output_filename_input.setEnabled(False)
        self.output_filename_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.output_filename_checkbox, self.output_filename_input))
        self.output_filename_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("output_filename_checkbox", self.output_filename_checkbox.isChecked()))
        self.output_filename_input.textChanged.connect(
            lambda: self.settings.setValue("output_filename_input", self.output_filename_input.text())
        )
        self.options_layout.addWidget(self.output_filename_checkbox)
        self.options_layout.addWidget(self.output_filename_input)

        # 输出路径
        self.select_output_layout = QHBoxLayout()
        self.output_dir_checkbox = QCheckBox("选择输出路径 (-o):")
        self.output_dir_input = QLineEdit(self)
        self.output_dir_btn = QPushButton("浏览", self)
        self.output_dir_btn.setEnabled(False)
        self.output_dir_input.setEnabled(False)
        self.output_dir_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.output_dir_checkbox, self.output_dir_input, self.output_dir_btn))
        self.output_dir_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("output_dir_checkbox", self.output_dir_checkbox.isChecked()))
        self.output_dir_input.textChanged.connect(
            lambda: self.settings.setValue("output_dir_input", self.output_dir_input.text())
        )
        self.output_dir_btn.clicked.connect(self.browse_output_dir)
        self.options_layout.addWidget(self.output_dir_checkbox)
        self.select_output_layout.addWidget(self.output_dir_input)
        self.select_output_layout.addWidget(self.output_dir_btn)
        self.options_layout.addLayout(self.select_output_layout)

        self.select_cookies_layout = QHBoxLayout()
        self.cookies_checkbox = QCheckBox("加载Cookies文件 (-c):")
        self.cookies_input = QLineEdit(self)
        self.cookies_dir_btn = QPushButton("浏览", self)
        self.cookies_dir_btn.setEnabled(False)
        self.cookies_input.setEnabled(False)
        self.cookies_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.cookies_checkbox, self.cookies_input, self.cookies_dir_btn))
        self.cookies_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("cookies_checkbox", self.cookies_checkbox.isChecked()))
        self.cookies_input.textChanged.connect(
            lambda: self.settings.setValue("cookies_input", self.cookies_input.text()))
        self.cookies_dir_btn.clicked.connect(self.browse_cookies_file)
        self.options_layout.addWidget(self.cookies_checkbox)
        self.select_cookies_layout.addWidget(self.cookies_input)
        self.select_cookies_layout.addWidget(self.cookies_dir_btn)
        self.options_layout.addLayout(self.select_cookies_layout)

        self.timeout_checkbox = QCheckBox("设置超时时间 (-t):")
        self.timeout_input = QLineEdit(self)
        self.timeout_input.setEnabled(False)
        self.timeout_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.timeout_checkbox, self.timeout_input))
        self.timeout_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("timeout_checkbox", self.timeout_checkbox.isChecked()))
        self.timeout_input.textChanged.connect(
            lambda: self.settings.setValue("timeout_input", self.timeout_input.text()))

        self.options_layout.addWidget(self.timeout_checkbox)
        self.options_layout.addWidget(self.timeout_input)

        self.debug_checkbox = QCheckBox("启用调试模式 (-d)")
        self.debug_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.debug_checkbox))
        self.debug_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("debug_checkbox", self.debug_checkbox.isChecked()))
        self.options_layout.addWidget(self.debug_checkbox)

        self.select_urls_layout = QHBoxLayout()
        self.input_file_checkbox = QCheckBox("从文件读取URLs (-I):")
        self.input_file_input = QLineEdit(self)
        self.input_file_btn = QPushButton("浏览", self)
        self.input_file_btn.setEnabled(False)
        self.input_file_input.setEnabled(False)
        self.input_file_checkbox.stateChanged.connect(
            lambda:self.toggle_input(self.input_file_checkbox, self.input_file_input, self.input_file_btn))
        self.input_file_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("input_file_checkbox", self.input_file_checkbox.isChecked()))
        self.input_file_input.textChanged.connect(
            lambda: self.settings.setValue("input_file_input", self.input_file_input.text()))

        self.input_file_btn.clicked.connect(self.browse_urls_file)
        self.options_layout.addWidget(self.input_file_checkbox)
        self.select_urls_layout.addWidget(self.input_file_input)
        self.select_urls_layout.addWidget(self.input_file_btn)
        self.options_layout.addLayout(self.select_urls_layout)

        # 其他选项
        self.password_checkbox = QCheckBox("设置视频访问密码 (-P):")
        self.password_input = QLineEdit(self)
        self.password_input.setEnabled(False)
        self.password_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.password_checkbox, self.password_input))
        self.password_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("password_checkbox", self.password_checkbox.isChecked()))
        self.password_input.textChanged.connect(
            lambda: self.settings.setValue("password_input", self.password_input.text())
        )
        self.options_layout.addWidget(self.password_checkbox)
        self.options_layout.addWidget(self.password_input)

        self.playlist_checkbox = QCheckBox("下载播放列表 (-l)")
        self.playlist_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.playlist_checkbox))
        self.playlist_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("playlist_checkbox", self.playlist_checkbox.isChecked()))
        self.options_layout.addWidget(self.playlist_checkbox)

        self.auto_rename_checkbox = QCheckBox("自动重命名同名文件 (-a)")
        self.auto_rename_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.auto_rename_checkbox))
        self.auto_rename_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("auto_rename_checkbox", self.auto_rename_checkbox.isChecked()))
        self.options_layout.addWidget(self.auto_rename_checkbox)

        self.insecure_checkbox = QCheckBox("忽略SSL错误 (-k)")
        self.insecure_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.insecure_checkbox))
        self.insecure_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("insecure_checkbox", self.insecure_checkbox.isChecked()))
        self.options_layout.addWidget(self.insecure_checkbox)

        self.m3u8_checkbox = QCheckBox("使用m3u8下载 (-m)")
        self.m3u8_checkbox.stateChanged.connect(
            lambda: self.toggle_input(self.m3u8_checkbox))
        self.m3u8_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("m3u8_checkbox", self.m3u8_checkbox.isChecked()))
        self.options_layout.addWidget(self.m3u8_checkbox)

        # 代理设置
        self.proxy_layout = QHBoxLayout()
        self.use_proxy_checkbox = QCheckBox("使用代理 (-x -s):")
        self.proxy_type_combo = QComboBox(self)
        self.proxy_type_combo.addItems(["HTTP", "SOCKS5"])
        self.proxy_type_combo.setMinimumSize(50, 45)
        self.proxy_input = QLineEdit(self)
        self.proxy_input.setPlaceholderText("输入代理地址 (如: 127.0.0.1:8080)")
        self.proxy_input.setEnabled(False)
        self.proxy_type_combo.setEnabled(False)
        self.use_proxy_checkbox.stateChanged.connect(
            lambda: self.toggle_proxy(self.use_proxy_checkbox, self.proxy_type_combo, self.proxy_input))
        self.use_proxy_checkbox.stateChanged.connect(
            lambda: self.settings.setValue("use_proxy_checkbox", self.use_proxy_checkbox.isChecked()))
        self.proxy_input.textChanged.connect(
            lambda: self.settings.setValue("proxy_input", self.proxy_input.text()))
        self.proxy_type_combo.currentTextChanged.connect(
            lambda: self.settings.setValue("proxy_type_combo", self.proxy_type_combo.currentText()))
        self.options_layout.addWidget(self.use_proxy_checkbox)
        self.proxy_layout.addWidget(self.proxy_type_combo)
        self.proxy_layout.addWidget(self.proxy_input)
        self.options_layout.addLayout(self.proxy_layout)

        main_layout.addLayout(self.options_layout)
        self.setLayout(main_layout)
        self.setWindowTitle("you-get 下载器")
        self.setGeometry(780, 200, 1000, 600)

    def toggle_input(self, checkbox, *widgets):
        """启用或禁用输入框和按钮，并将所有文字和控件颜色改为灰色或黑色"""
        for widget in widgets:
            widget.setEnabled(checkbox.isChecked())
        if checkbox.isChecked():
            checkbox.setStyleSheet("color: white;")
            for widget in widgets:
                widget.setStyleSheet("color: white;")
        else:
            checkbox.setStyleSheet("color: grey;")
            for widget in widgets:
                widget.setStyleSheet("color: grey;")

    def toggle_proxy(self, checkbox, *widgets):
        """控制代理的启用和禁用"""
        self.toggle_input(checkbox, *widgets)

    def browse_output_dir(self):
        directory = QFileDialog.getExistingDirectory(self, "选择输出目录")
        if directory:
            self.output_dir_input.setText(directory)

    def browse_cookies_file(self):
        # 打开文件对话框，让用户选择一个 .sqlite 或 .txt 文件
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择文件", "", "SQLite Files (*.sqlite);;Text Files (*.txt)"
        )

        if file_path:
            # 如果用户选择了文件，并且路径非空，则设置文本框内容
            self.cookies_input.setText(file_path)

    def browse_urls_file(self):
        # 打开文件对话框，让用户选择一个 .sqlite 或 .txt 文件
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择文件", "", "Text Files (*.txt)"
        )

        if file_path:
            # 如果用户选择了文件，并且路径非空，则设置文本框内容
            self.input_file_input.setText(file_path)

    def is_m3u8_url(self, url):
        # 解析 URL
        parsed_url = urlparse(url)
        # 获取路径部分
        path = parsed_url.path
        # 检查路径是否以 .m3u8 结尾
        return path.lower().endswith('.m3u8')

    def start_download(self):
        url = self.url_input.text()
        if not self.input_file_checkbox.isChecked():
            if not url:
                QMessageBox.warning(self, "警告", "请输入有效的URL！")
                return
            elif self.m3u8_checkbox.isChecked() and not self.is_m3u8_url(url):
                QMessageBox.warning(self, "警告", "请输入有效的M3U8地址！")
                return

        cmd = ['you-get']

        # 处理参数选项
        if self.no_merge_checkbox.isChecked():
            cmd.append('-n')

        if self.no_caption_checkbox.isChecked():
            cmd.append('--no-caption')

        if self.postfix_checkbox.isChecked():
            cmd.append('--postfix')

        if self.prefix_checkbox.isChecked():
            prefix = self.prefix_input.text()
            if prefix:
                cmd += ['--pre', prefix]

        if self.force_checkbox.isChecked():
            cmd.append('-f')

        if self.skip_checkbox.isChecked():
            cmd.append('--skip-existing-file-size-check')

        if self.format_checkbox.isChecked():
            format_option = self.format_input.text()
            if format_option:
                cmd += ['-F', format_option]

        if self.output_filename_checkbox.isChecked():
            output_filename = self.output_filename_input.text()
            if output_filename:
                cmd += ['-O', output_filename]

        if self.output_dir_checkbox.isChecked() and self.output_dir_input.text():
            output_dir = self.output_dir_input.text()
            cmd += ['-o', output_dir]
        else:
            # 如果没有提供输出目录，则使用系统默认的下载目录
            output_dir = Path.home() / "Downloads"
            if not output_dir.exists():
                output_dir.mkdir(parents=True, exist_ok=True)
            print(output_dir)
            cmd += ['-o', str(output_dir)]
            print(cmd)

        if self.cookies_checkbox.isChecked():
            cookies_file = self.cookies_input.text()
            if cookies_file:
                cmd += ['-c', cookies_file]

        if self.timeout_checkbox.isChecked():
            timeout = self.timeout_input.text()
            if timeout:
                cmd += ['-t', timeout]

        if self.debug_checkbox.isChecked():
            cmd.append('-d')

        if self.input_file_checkbox.isChecked():
            input_file = self.input_file_input.text()
            if input_file:
                cmd += ['-I', input_file]

        if self.password_checkbox.isChecked():
            password = self.password_input.text()
            if password:
                cmd += ['-P', password]

        if self.playlist_checkbox.isChecked():
            cmd.append('-l')

        if self.auto_rename_checkbox.isChecked():
            cmd.append('-a')

        if self.insecure_checkbox.isChecked():
            cmd.append('-k')

        if self.m3u8_checkbox.isChecked():
            cmd.append('-m')

        # 代理设置
        if self.use_proxy_checkbox.isChecked():
            proxy_type = self.proxy_type_combo.currentText()
            proxy_url = self.proxy_input.text()

            if proxy_type == "HTTP" and proxy_url:
                cmd += ['-x', proxy_url]
            elif proxy_type == "SOCKS5" and proxy_url:
                cmd += ['-s', proxy_url]

        # 添加下载参数
        if not self.input_file_checkbox.isChecked():
            # 添加URL
            cmd.append(url)

        # 打开新的下载窗口
        download_window = DownloadWindow("下载详情", cmd, self.settings)
        download_window.show()

    def show_info(self):
        url = self.url_input.text()
        if not url:
            QMessageBox.warning(self, "警告", "请输入有效的下载地址！")
            return

        cmd = ['you-get']

        info_type = self.info_type_combo.currentText()

        if info_type == "Info":
            cmd += ['-i', url]
        elif info_type == "Info with url":
            cmd += ['-u', url]
        elif info_type == "JSON Format":
            cmd += ['--json', url]

        # 打开新的信息窗口
        info_window = InfoWindow("信息详情", cmd)
        info_window.show()

    def play_video(self):
        url = self.url_input.text()
        if not url:
            QMessageBox.warning(self, "警告", "请输入有效的播放地址！")
            return

        if not self.player_input.text():
            QMessageBox.warning(self, "警告", "请输入播放器名称")
            return

        cmd = ['you-get', '-p', self.player_input.text(), url]

        self.thread = PlayerThread(cmd)
        self.thread.start()

    def load_settings(self):
        self.info_type_combo.setCurrentText(self.settings.value("info_type_combo", "Info"))
        # self.player_input.setText(self.settings.value("player_input", ""))
        self.no_merge_checkbox.setChecked(self.settings.value("no_merge_checkbox", False, type=bool))
        self.no_caption_checkbox.setChecked(self.settings.value("no_caption_checkbox", False, type=bool))
        self.postfix_checkbox.setChecked(self.settings.value("postfix_checkbox", False, type=bool))
        self.prefix_checkbox.setChecked(self.settings.value("prefix_checkbox", False, type=bool))
        self.prefix_input.setText(self.settings.value("prefix_input", ""))
        self.force_checkbox.setChecked(self.settings.value("force_checkbox", False, type=bool))
        self.skip_checkbox.setChecked(self.settings.value("skip_checkbox", False, type=bool))
        self.format_checkbox.setChecked(self.settings.value("format_checkbox", False, type=bool))
        self.format_input.setText(self.settings.value("format_input", ""))
        self.output_filename_checkbox.setChecked(self.settings.value("output_filename_checkbox", False, type=bool))
        self.output_filename_input.setText(self.settings.value("output_filename_input", ""))
        self.output_dir_checkbox.setChecked(self.settings.value("output_dir_checkbox", False, type=bool))
        self.output_dir_input.setText(self.settings.value("output_dir_input", ""))
        self.cookies_checkbox.setChecked(self.settings.value("cookies_checkbox", False, type=bool))
        self.cookies_input.setText(self.settings.value("cookies_input", ""))
        self.timeout_checkbox.setChecked(self.settings.value("timeout_checkbox", False, type=bool))
        self.timeout_input.setText(self.settings.value("timeout_input", ""))
        self.debug_checkbox.setChecked(self.settings.value("debug_checkbox", False, type=bool))
        self.input_file_checkbox.setChecked(self.settings.value("input_file_checkbox", False, type=bool))
        self.input_file_input.setText(self.settings.value("input_file_input", ""))
        self.password_checkbox.setChecked(self.settings.value("password_checkbox", False, type=bool))
        self.password_input.setText(self.settings.value("password_input", ""))
        self.playlist_checkbox.setChecked(self.settings.value("playlist_checkbox", False, type=bool))
        self.auto_rename_checkbox.setChecked(self.settings.value("auto_rename_checkbox", False, type=bool))
        self.insecure_checkbox.setChecked(self.settings.value("insecure_checkbox", False, type=bool))
        self.m3u8_checkbox.setChecked(self.settings.value("m3u8_checkbox", False, type=bool))
        self.use_proxy_checkbox.setChecked(self.settings.value("use_proxy_checkbox", False, type=bool))
        self.proxy_type_combo.setCurrentText(self.settings.value("proxy_type_combo", "HTTP"))
        self.proxy_input.setText(self.settings.value("proxy_input", ""))

        # 重新启用/禁用相关控件
        self.toggle_input(self.no_merge_checkbox)
        self.toggle_input(self.no_caption_checkbox)
        self.toggle_input(self.postfix_checkbox)
        self.toggle_input(self.prefix_checkbox, self.prefix_input)
        self.toggle_input(self.force_checkbox)
        self.toggle_input(self.skip_checkbox)
        self.toggle_input(self.format_checkbox, self.format_input)
        self.toggle_input(self.output_filename_checkbox, self.output_filename_input)
        self.toggle_input(self.output_dir_checkbox, self.output_dir_input, self.output_dir_btn)
        self.toggle_input(self.cookies_checkbox, self.cookies_input, self.cookies_dir_btn)
        self.toggle_input(self.timeout_checkbox, self.timeout_input)
        self.toggle_input(self.debug_checkbox)
        self.toggle_input(self.input_file_checkbox, self.input_file_input, self.input_file_btn)
        self.toggle_input(self.password_checkbox, self.password_input)
        self.toggle_input(self.playlist_checkbox)
        self.toggle_input(self.auto_rename_checkbox)
        self.toggle_input(self.insecure_checkbox)
        self.toggle_input(self.m3u8_checkbox)
        self.toggle_proxy(self.use_proxy_checkbox, self.proxy_type_combo, self.proxy_input)

    # def closeEvent(self, event):
    #     # 保存设置
    #     self.save_settings()
    #     event.accept()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    downloader = DownloaderApp()
    downloader.setWindowIcon(QIcon(os.path.join(os.path.dirname(os.path.abspath(__file__)), "static", "logo.png")))
    downloader.show()
    sys.exit(app.exec_())